package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.CompanyDao;
import com.cn.wanxi.dao.impl.CompanyImpl;
import com.cn.wanxi.model.CompanyModel;
import com.cn.wanxi.service.CompanyService;
import redis.clients.jedis.Jedis;

public class CompanyServiceRedisImpl implements CompanyService {
    /**
     * 0.要引入第三方jar包
     * 1.判断当前缓存里面是否有数据
     * 2.如果有，则取缓存数据
     * 3.如果没有，则取数据库
     * 4.如果管理员修改了数据，我们应该及时更新redis数据
     *
     * @return
     */
    @Override
    public CompanyModel getCompanyModel() {
        final CompanyModel[] companyModel = {new CompanyModel()};
        for (int i = 0; i < 500; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    companyModel[0] = findRedis();
                }
            }, "线程" + i + "开始运行").start();
        }
        return companyModel[0];
    }

    private CompanyModel findRedis() {
        Jedis jedis = new Jedis();
        boolean isRedis = jedis.exists("logo");

        CompanyModel companyModel = new CompanyModel();
        if (isRedis) {
            companyModel.setLogo(jedis.get("logo"));
            companyModel.setPhone(jedis.get("phone"));
            companyModel.setNet(jedis.get("net"));
            companyModel.setEmail(jedis.get("email"));
            companyModel.setAddress(jedis.get("address"));
            companyModel.setVersion(jedis.get("version"));
            System.out.println("redis");
        } else {
            CompanyDao companyDao = new CompanyImpl();
            companyModel = companyDao.getCompanyModel();
            jedis.set("logo", companyModel.getLogo());
            jedis.set("phone", companyModel.getPhone());
            jedis.set("net", companyModel.getNet());
            jedis.set("email", companyModel.getEmail());
            jedis.set("address", companyModel.getAddress());
            jedis.set("version", companyModel.getVersion());
            System.out.println("mysql");
        }
        return companyModel;
    }

    /**
     * 除了增加，修改，和删除也需要去删除logo的key值
     *
     * @param companyModel
     * @return
     */
    public String add(CompanyModel companyModel) {
        CompanyDao companyDao = new CompanyImpl();
        int result = companyDao.add(companyModel);
        if (result > 0) {
            Jedis jedis = new Jedis();
//            jedis.set("logo", companyModel.getLogo());
            jedis.del("logo");
        }
        return result > 0 ? "success" : "error";
    }
}
